package com.sharding.test.utils;

import java.net.InetAddress;

public final class IPUtils {

	/**
	 * 获取主机IP地址
	 * 
	 * @return
	 */
	public static String getHostIp() {
		try {
			InetAddress addr = InetAddress.getLocalHost();
			return addr.getHostAddress();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 获取主机IP地址(数字)
	 * @return
	 */
	public static Long getHostNumberIp() {
		Long ip = 0L;
		try {
			InetAddress addr = InetAddress.getLocalHost();
			String ipAddr = addr.getHostAddress();
			ip = ipToNumber(ipAddr);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return ip;
	}
	
	/**
	 * 把IP地址转成Long
	 * @param ip
	 * @return
	 */
	public static Long ipToNumber(String ip) {    
		Long ipLong = 0L; 
		String[] ipNumbers = ip.split("\\.");
		for (String ipNumber : ipNumbers) {
			ipLong = ipLong << 8 | Integer.parseInt(ipNumber);
		}
		return ipLong;   
	} 

}
